/**
 * Pangolin IM Server
 * autor:   yiyefangzhou24
 * email:   yiyefangzhou24@qq.com
 * data:    21/10/1
 */


#include "log.h"

/* 增加互斥锁 */
pthread_mutex_t LOG_MUTEX;
int log_debug = false;
char log_path[128] = { 0 };

void _get_filename(char * file);
void _get_time(char * ctime);

void _get_filename(char * file){
    time_t timep;
    time(&timep);
    struct tm  * curr_time = localtime(&timep);
    sprintf(file , "%schatserver_%d_%d.log" , log_path , (curr_time->tm_year+1900) ,  \
        (curr_time->tm_mon+1));
}

void _time(char * ctime){
    time_t timep;
    time(&timep);
    struct tm  * curr_time = localtime(&timep);
    sprintf(ctime , "%d/%d/%d %d:%d:%d" , (curr_time->tm_year+1900) ,  \
        (curr_time->tm_mon+1) , curr_time->tm_mday , curr_time->tm_hour ,  \
        curr_time->tm_min ,curr_time->tm_sec);
}

void LOG_INIT(bool debug,char * path){
    pthread_mutex_init(&LOG_MUTEX, NULL);
    log_debug = debug;
    strcpy(log_path , path);
}

void LOG_DESTORY(){
    pthread_mutex_destroy(&LOG_MUTEX);
}

//可能多线程调用，需要原子操作
void LOG(const char * format, ...){
    pthread_mutex_lock(&LOG_MUTEX);
    va_list ap;
    va_start(ap , format);
    if(log_debug){
        char ctime[64] = { 0 };
        _time(ctime);
        printf("%s " , ctime);
        vprintf(format , ap);
        printf("\n");
    }else{
        char file[256] = { 0 };
        _get_filename(file);
        char ctime[64] = { 0 };
        _time(ctime);
        FILE *fp = fopen(file , "a+");
        fprintf(fp , "%s " , ctime);
        vfprintf(fp , format , ap);
        fprintf(fp , "\r\n");
        fclose(fp);
    }
    va_end(ap);
    pthread_mutex_unlock(&LOG_MUTEX);
}